$(function() {  
    //主页初始化.  
    page.showMask('loading');    
    $(document.body).fadeIn('slow');   
        
    $(document.body).keydown(function(e){
        if( e.ctrlKey && ( e.keyCode == 83 ) ) {    
            return false;
        }
    });
            
    page.on('activeStateChange', function(isActive){
        if(isActive){
            ujs.browser.WebNotification.hideLastNotification();
        }        
        if(isActive && window.sessionList && window.sessionList.$wrapper && page.isSearching !== true){
            var $current = sessionList.$wrapper.find('.sessionListItem.current'); 
            var type = $current.attr('type');
            if(type && type.indexOf('chat') > -1 && parseInt($current.find('.unreadMsgCount').text()) > 0){
                $current.trigger('click');
            }
        }
    });
    
    //创建本地缓存对象.
    if(window.ChatGroupDataAdapter){
        page.chatGroupStore = new ChatGroupStore('id', ChatGroupDataAdapter, UpdateChatGroupDataAdapter);
        page.urlStore = new UrlStore('id', UrlDataAdapter, UpdateUrlDataAdapter);
        page.chatMsgStore = {
            addItem : function(topic){
                var msgStore = this[topic['teid']];                                    
                if(!msgStore){
                    msgStore = new ChatMsgStore();
                    this[topic['teid']] = msgStore;                                        
                }                
                msgStore.addItem(topic);
            }
        };
    }
    
    //获取当前用户地理位置.    
    ujs.browser.geo.getCurrentPosition(function(position){
        page.position = position;
    });     
    
    //未读数提醒.
    var lastCount = 0;
    page.setUnread = function(flag, isMsg){   
        var unread = sessionList.getUnread();
        var count = sessionList.getUnreadSC();
                
        if(isMsg !== false && flag && !page.isActive && unread > 0){
            var msg = page.lastMsg || msg;
            if(msg){
                ujs.browser.WebNotification.show({
                    msg : msg.cut(50),
                    icon : '/ujs/app/im/images/login/logo2.png',
                    title : '{0} unread message(s) from {1} contact(s)'.format(unread, count)
                });
            }
        }
        
        if(flag && unread == 0){
            ujs.browser.WebNotification.hideLastNotification();
        }    
        
        if(unread){
            document.title = 'AcuCom({0})'.format(unread);
        } else {
            document.title = 'AcuCom';
        }
    };
    
    //--------------------------------------------------------------------------------------------------
    
    page.$sessionList = $('body').find('.sessionList');
    page.$mainContent = $('body').find('.mainContent');
    page.defLeftWidth = $(window).width()/5;    //默认1/5 of page width.    
    page.isDraging = false;
    var $vSpliter = $('body').find('.sessionList .v_spliter');
    
    var defLeftWidth = $.cookie('defLeftWidth');
    if(defLeftWidth){
        defLeftWidth = parseInt(defLeftWidth);
        if(defLeftWidth > 0){
            page.defLeftWidth = defLeftWidth;  
        }        
    }
    page.$sessionList.css('width', page.defLeftWidth);
    page.$mainContent.css('width', 'calc(100% - {0}px)'.format(page.defLeftWidth + 2));
                    
    $vSpliter.bind('mousedown', function(e){
        page.isDraging = true;    
        page.startX = e.pageX;                          
        $('body').addClass('unselectable');               
    });
    $(document.body).bind({
        'mouseup' : function(e){                        
            page.isDraging = false;
            $('body').removeClass('unselectable');
        },
        'mousemove' : function(e){
            if(page.isDraging){                            
                var offsetX = e.pageX - page.startX;
                page.startX = e.pageX;
                page.defLeftWidth += offsetX;
                
                page.defLeftWidth = page.defLeftWidth.constraintRegion(230,1000);
                
                page.$sessionList.css('width', page.defLeftWidth);
                page.$mainContent.css('width', 'calc(100% - {0}px)'.format(page.defLeftWidth + 2));
                
                $('#searchResult').css('width', page.defLeftWidth);
                
                $.cookie('defLeftWidth', page.defLeftWidth, {
                    expires : Date.nowDateObj().add('y', 1000)
                });                
            }
        }
    });
                
    //--------------------------------------------------------------------------------------------------
    
    /**
     * 初始化页面权限信息.
     */
    page.on('init', function() {
        //card layout
        this.contentCardLayout = $('.mainContent').cardLayout({}).data('cardLayout');
        if(!this.contentCardLayout){
            return false;
        }
        
        this.contentCardLayout.addItem('dashboard', dashboard).showItem('dashboard');        
        /**
         * SessionList部分.
         */
        var sessionListTab = $('#sessionListTab').tabControl({}).data('tabControl');       
        if(sessionListTab){ 
            sessionListTab.addTabItem({
                id : 'allSessionList',
                title : 'Session List',
                html : [
                    '<div class="sessionListTitle">',
                        '<span id="searchSessionList"></span>',
                    '</div>',
                    '<section id="groupSessionList" style="height:calc(100% - 38px);overflow:auto;border-right: solid 1px #C4BFD6;">',
                        '<ul></ul>',
                    '</section>'
                ].join('')
            }, function($allSessionList){
                sessionList.init($allSessionList.find('#groupSessionList > ul'));
                sessionSearch.init($allSessionList.find('#searchSessionList'));            
            });
        }
               
        var searchTab = $('#searchResult').tabControl({
            style : 'searchResult'
        }).data('tabControl');
        
        if(searchTab){            
            page.searchTab = searchTab;            
            //消息列表
            searchTab.addTabItem({
                id : 'msgList',         
                icon : ujs.getRes('images/common16/chat.png'),   
                title : 'Msg',         
                html : [
                    '<div class="msgResult" />'                
                ]
            }, function($msgList){            
                $msgList.find('.msgResult').listView({
                        itemTmp : [
                            '<div class="msgSearchItem <%= o.deleted ? "deleted" : "" %>" id="<%=o.id%>" teid="<%=o.teid%>" seq="<%=o.seq%>">',
                                '<img src="<%= ujs.browser.loc.addQuery( (o.icon || o.user.icon || ""), {w:200}) %>" style="width: 50px;height: 50px;float: left;margin-right: 3px;"/>',
                                '<div>',
                                    '<%=o.content ? o.content.highlight() : ""%><br/>',
                                    lan('misc.from') + '<%=o.user ? o.user.name : "Unknown" %><br/>',
                                    lan('misc.atSession') + '<a class="xxxxxxxxxx" teid="<%=o.teid%>" style="<%= o.deleted ? "text-decoration:line-through;" : "" %>" onclick="page.ss(this);return false;" href="#"><%= o.title || o.name %></a>',
                                '</div>',
                            '</div>'
                        ].join(''),
                        emptyTip : lan('app.im.search.noMsg'),
                        theme : 'userResultList',
                        events : {
                            itemClick : function($listViewItem){                            
                                var $target = $listViewItem.find('>.msgSearchItem'),
                                    id = $target.attr('id'),                            
                                    teid = $target.attr('teid'),
                                    seq = $target.attr('seq'),
                                    searchKey = $('.searchBox').val().trim();
                                    
                                //获取搜索高亮词.   
                                $.ajax({
                                    url : '/apis/chat/search/highlights?q={query}&t={topicEntityId}'.format({                                        
                                        query : encodeURIComponent('content:({key})'.format({
                                            key : searchKey
                                        })),
                                        topicEntityId : teid
                                    })
                                }).done(ujs.hr(function(msg) {                            
                                    var chatGroupEntity = page.chatGroupStore.getItem(teid) || {},
                                        chatPanel = page.contentCardLayout.getItem(id);
                                                         
                                    if(!chatPanel){
                                        chatPanel = new ChatPanel($.extend(true, {}, chatGroupEntity, {
                                            id : teid,
                                            deleted : $target.hasClass('deleted'),
                                            name : $target.find('.xxxxxxxxxx').text(),
                                            perm : {                                                
                                                prof: 1
                                            }
                                        }));
                                        chatPanel.mode = 'view';     
                                        chatPanel.middleSeq = seq;                                            
                                        chatPanel.keys = msg['highlights'];                             
                                        page.contentCardLayout.addItem(id, chatPanel);                                
                                    } else {
                                        chatPanel.setKeys(msg['highlights']);
                                    }           
                                    page.contentCardLayout.showItem(id);
                                    chatPanel.disableChatEditor();
                                }));                                  
                            }
                        }
                    }
                );
            });
            
            //用户列表
            searchTab.addTabItem({
                id : 'userList',
                icon : ujs.getRes('images/common16/user3.png'),
                title : 'user',
                html : [
                    '<div class="userResult" />'                
                ]
            }, function($userList){            
                $userList.find('.userResult').listView({
                        itemTmp : [
                            '<div id="<%=o.id%>" class="searchUserName">',
                                '<img src="<%=o.icon ? ujs.browser.loc.addQuery(o.icon, {w:200}) : ujs.getConfigRes("defUserIcon") %>" style="width: 50px;float: left;margin-right: 3px;" />',
                                '<div><%=o.name%><br/>' + lan('misc.from') + '<%= $.map(o.groups, function(group){return group["name"]}).join(", ") %></div>',
                            '</div>'
                        ].join(''),
                        emptyTip : lan('app.im.search.noUser'),
                        key : 'id',
                        theme : 'userResultList',
                        events : {
                            itemClick : function($listViewItem){}
                        }
                    }
                );      
            });
            
            //用户组列表
            searchTab.addTabItem({
                id : 'groupList',
                icon : ujs.getRes('images/common16/user-group.png'),
                title : 'group',
                html : [
                    '<div class="groupResult" />'                
                ]
            }, function($groupList){             
                $groupList.find('.groupResult').listView({
                        itemTmp : [
                            '<div class="searchUserName" id="<%=o.id%>">',
                                '<img src="<%= o.icon ? ujs.browser.loc.addQuery(o.icon, {w:200}) : ujs.getConfigRes("defGroupIcon") %>" style="width: 50px;float: left;margin-right: 3px;" />',
                                '<div><%=o.name%></div>',
                            '</div>'
                        ].join(''),
                        emptyTip : lan('app.im.search.noUserGroup'),
                        theme : 'groupResultList',
                        events : {
                            itemClick : function($listViewItem){}
                        }
                    }
                );             
            });
        }
    });
    
    page.ss = function(dom){
        var teid = $(dom).attr('teid');
        $.ajax({
            //特定session内搜索.
            url : '/apis/chat/search/topic?q={query}&l={limit}&o={offset}&t={teid}'.format({
                query : encodeURIComponent('content:({key}) OR (content_name:({key}) AND contentType:file)'.format({
                    key : $('.searchBox').val().trim()
                })),
                teid : teid,
                limit : 300,
                offset : 0
            })
        }).then(ujs.hr(function(msg) {                            
            $('.msgResult').data('listView').load(msg['topics']);
            page.searchTab.addTabHeaderThumb('msgList', msg['total'] || 0);
        }));
        return false;
    };
    
    page.sc = function(uid, cb){        
        var singleChat = page.chatGroupStore.getSingleChatByUser(uid);                    
        if(singleChat){
            sessionList.startSession(singleChat['id']);
            cb && cb();
        } else {                
            page.biz.createChatGroup(
                Object.toFormData({
                    chat : JSON.stringify({
                        type : 'singlechat',
                        uids : [uid]
                    })
                }), 
                function(msg){                            
                    //add local
                    page.biz.addChatGroupLocal(msg);                
                    sessionList.startSession(msg['te']['id']);
                    cb && cb();                            
                }
            );
        }  
    };
    
    page.sc2 = function(dom, cb){
        var $this = $(dom);
        ujs.ui.Dialog.get( ChatGroupDialog, {
            title : lan('app.im.chat.newChat'),
            root : [{
                id : $this.attr('id'),
                name : $this.attr('name'),
                icon : $this.attr('icon')
            }]
        }); 
    };

    page.needRepare = false;
    page.cid = '';
    
    if(window.ChatGroupDataAdapter){
        page.on('init', function(){
            //建立Comet通道.
            this.pipe = new CometPipe({
                api : '/events?v=' + appConfig.version
            });
            //Comet通道响应处理.
            this.pipe.on('response', function(msg){
                var _this = this;
                //权限应用.
                if(msg['perm']){                    
                    initHeader(msg['perm']);
                }
                if(this.ajaxType == 'post'){
                    page.hideMask();
                    //TODO dialog的mask与此冲突.
                    ujs.browser.WebNotification.showEnableNotificationTip(); 
                }
                if(msg['c']){
                    this.api = ujs.browser.loc.addQuery(this.api, {
                        c : msg['c']
                    });
                }
                this.api = ujs.browser.loc.addQuery(this.api, {
                    h : !page.isActive
                });
                
                var isContinueRequest = true;                
                //事件分配器.
                EventDispatcher.parseEvents(
                    msg['events'],
                    function(evt){
                        if(evt['eventType'] === EventType.COMMAND && evt['commandType'] === 'sync'){
                            //sync, 同步数据.
                            isContinueRequest = false;                  
                            page.needRepare = true;      
                                                  
                            if(evt['set-cid']){
                                page.cid = evt['set-cid'];
                            }
                            
                            if(page && page.chatGroupStore && page.urlStore){
                                var chatGroupEntitys = $('#chatGroupList .cardWrapper').map(function(){
                                    var teid=$(this).attr('card-id'); 
                                    return page.chatGroupStore.getItem(teid);
                                }).map(function(){
                                    return {
                                        eid : this.id,
                                        utime : this.updateTime,
                                        seq : this.latestSeq,
                                        cseq : this.currentSeq,
                                        type : 20
                                    };
                                }).get();
                                
                                var urlEntitys = $('#eventList, #surveyList, #urlList, #pageList').find('.cardWrapper').map(function(){
                                    var ueid=$(this).attr('card-id'); 
                                    return page.urlStore.getItem(ueid);
                                }).map(function(){
                                    return {
                                        eid : this.id,
                                        utime : this.updateTime,                                    
                                        type : 10
                                    };
                                }).get();
                                var nowEntitys = chatGroupEntitys.concat(urlEntitys);
                            } else {
                                var nowEntitys = [];
                            }
                            
                            return _this.request({ entities :  nowEntitys});
                        }
                    },
                    function(){
                        if(page.needRepare){         
                            (function(){
                                //修复当前session.
                                var activePanel = ChatPanel.getActiveChatPanel();
                                if(activePanel){
                                    var currentSeq = activePanel.chatView.getLastSeq();
                                    var latestSeq = activePanel.chatGroupEntity['latestSeq'];
                                    var count = latestSeq - currentSeq;
                                    if(count > 0) {
                                        page.biz.getMsgListAsRead(activePanel.chatGroupEntity['id'], latestSeq, count).done(function(msg){                                                                                 
                                            activePanel.chatView.addTopic(msg['topics'].reverse());
                                            var tteid = activePanel.chatGroupEntity.id;
                                            sessionList.updateItem(tteid, function(teObj){
                                                var newItem = page.chatGroupStore.getItem(tteid);                                          
                                                if(newItem){
                                                    if(newItem['currentSeq'] > teObj['currentSeq']) {
                                                        teObj['currentSeq'] = newItem['currentSeq'];
                                                    }
                                                    if(newItem['latestSeq'] > teObj['latestSeq']) {
                                                        teObj['latestSeq'] = newItem['latestSeq'];
                                                    }
                                                }
                                            });
                                        });
                                    }    
                                }
                                //非当前session.
                                var $sessionItems = sessionList.$wrapper.find('.sessionListItem:not(.current)');  
                                $sessionItems.each(function(){
                                    var sid = $(this).attr('sid');
                                    var newItem = page.chatGroupStore.getItem(sid);
                                    if(newItem){
                                        sessionList.updateItem(sid, function(teObj){
                                            var newItem = page.chatGroupStore.getItem(sid);                                          
                                            if(newItem){
                                                if(newItem['currentSeq'] > teObj['currentSeq']) {
                                                    teObj['currentSeq'] = newItem['currentSeq'];
                                                }
                                                if(newItem['latestSeq'] > teObj['latestSeq']) {
                                                    teObj['latestSeq'] = newItem['latestSeq'];
                                                }
                                            }
                                        });
                                    }
                                });            
                                //修复read count
                                if(activePanel){
                                    if(activePanel.chatGroupEntity.type === 'singlechat'){                                    
                                        page.biz.getParticipantReadSeq(activePanel.chatGroupEntity['te'], function(seq){
                                           activePanel.chatView.setMsgReaded(seq);
                                        });
                                    } else {
                                        $('.readerListWrapper').remove();
                                        (function(){
                                            page.biz.getReadCount();
                                        }).defer(200);
                                    }
                                }                                            
                                page.needRepare = false;    
                            }).defer(500);
                        }
                        if(isContinueRequest){                            
                            _this.request();
                        }      
                    }
                );
            });
            //Comet通道错误处理.
            this.pipe.on('error', function(msg){
                if(msg){                    
                    if(msg['code'] == 1060 || msg['code'] == 1219 || msg['code'] == 1220){ 
                        ujs.util.debug.log({code : 'toLoginPage:' + msg['code']});  
                        ujs.browser.loc.toLoginPage(
                            false, 
                            msg['code'] == 1219 ? { autologin : 1 } : { autologin : 0 }
                        );
                    }
                    if(msg['code'] == 503){
                        page.findAuth.start();
                    }
                }
            });
            
            this.pipe.start();
        });
    }
    
    //循环请求位置.
    page.locTimer = new ujs.Timer({
        timerFun : function(){    
            if(page.isActive){
                if(window.ChatPanel){         
                    var chatPanel = ChatPanel.getActiveChatPanel();
                    if(chatPanel && chatPanel.chatGroupEntity && chatPanel.chatGroupEntity['type'] == 'locationalert'){
                        chatPanel.scan();
                    }
                }
            }
        },
        interval : 1000 * 10
    });
    page.locTimer.start();
    
    //补全消息.
    page.chatTimer = new ujs.Timer({
        async : true,
        timerFun : function(){    
            if(page.isActive){
                if(window.ChatPanel){         
                    var chatPanel = ChatPanel.getActiveChatPanel();
                    if(chatPanel && chatPanel.chatGroupEntity){
                        var chatView = chatPanel.chatView;
                        var $items = chatPanel.chatView.$wrapper.find('.chatMsgItem');
                        var firstSeq = parseInt($items.first().attr('seq')) || 0;
                        var lastSeq = parseInt($items.last().attr('seq')) || 0;                        
                        if(lastSeq > firstSeq){
                            var lackSeq = [];
                            for(var m=firstSeq; m<=lastSeq; m++){
                                lackSeq.push(m);
                            }
                            for(var i=0; i<$items.length; i++){
                                var seqTmp = parseInt($($items[i]).attr('seq'));
                                lackSeq.remove(seqTmp);
                            }
                            if(lackSeq && lackSeq.length > 0){
                                $.get('/apis/chat/{0}/topicseqs?seqs={1}'.format(chatPanel.chatGroupEntity['id'], lackSeq.join(',')), function(msg){                                    
                                    //var topics = msg['topics'];
                                    chatPanel.chatView.addTopic(msg['topics']);
                                    page.chatTimer.next();                                        
                                });
                            } else{
                                page.chatTimer.next();
                            }
                        } else {
                            page.chatTimer.next();
                        }
                    } else {
                        page.chatTimer.next();
                    }
                } else {
                    page.chatTimer.next();
                }
            } else {
                page.chatTimer.next();
            }
        },
        interval : 1000 * 2
    });
    page.chatTimer.start();
    
    page.findAuth = new ujs.Timer({
        async : true,
        timerFun : function(){
            var _this = this;
            $.get('/oauth/client/find').done(function(msg){
                if(msg && msg['result'] == 'login'){
                    ujs.util.debug.log({code : 'toLoginPage:' + msg['code']});  
                    ujs.browser.loc.toLoginPage(false, { autologin : 1 } );
                } else {
                    _this.next();
                }    
            });    
        },
        interval : 1000 * 2
    });
    
    window.onerror = function(msg, url, lineNo, colNo, errorObj)  {        
        ujs.util.debug.log({
            msg : msg,
            url : url,
            lineNo : lineNo,
            colNo : colNo,
            attach : errorObj
        });
    };

    page.init({
        disableContextmenu : false
    });

    //错误面板.
    page.errorPanel = $.FloatCard.create({
        theme : 'errorPanel',
        style : {
            clear : 'both'
        }
    }).render('#floatCard');
    page.errorPanel.hide();
    page.errorPanel.on('show', function(){
        $('#main').css('height', 'calc(100% - 108px)');
    });
    page.errorPanel.on('hide', function(){
        $('#main').css('height', 'calc(100% - 82px)');
    });

    $(document.body).click(function(){
        $('.readerListWrapper').remove();
    });

    page.mapLoc = {};

    window.onunload = function() {
        $(document.body).fadeOut(100);      
    };

    //acucom业务类实例.
    page.biz = new Biz();  
});